const express = require("express");
const router = express.Router();

const config = require("../../config/config");
const ManagerModel = require("../../model/managerModel");
const NavModel = require("../../model/navModel");
const FocusModel = require("../../model/focusModel");
const ArticleCateModel = require("../../model/articleCateModel");
const ArticleModel = require("../../model/articleModel");

// 配置所有的 model
const appModel = { ManagerModel, NavModel, FocusModel, ArticleCateModel, ArticleModel };

router.get("/", (req, res) => {
    res.render("admin/main/index.html");
})

router.get("/welcome", async (req, res) => {
    res.send("欢迎来到后台管理中心");
})

// 公共的修改状态的接口
router.get("/changeStatus", async (req, res) => {
    // 1. 获取要修改数据的id
    // 2. 我们需要查询当前数据的状态
    // 3. 修改状态 0 -> 1 或 1 -> 0
    let id = req.query.id;
    let model = req.query.model + "Model"; // 要操作的数据模型（修改的表对应的model）
    let field = req.query.field; // 要修改的字段 status
    let json; // 要更新的数据
    const result = await appModel[model].find({ _id: id });
    if(result.length > 0) {
        // 获取需要更新的值
        const tempField = result[0][field];
        tempField == 1 ? json = { [field]: 0 } : json = { [field]: 1 }; // es6的属性名表达式
        await appModel[model].updateOne({ _id: id }, json);
        res.send({
            success: true,
            message: "修改状态成功"
        });
    } else {
        res.send({
            success: false,
            message: "修改状态失败"
        });
    }
});


// 公共的修改数字的接口
router.get("/changeNum", async (req, res) => {
    let id = req.query.id; /*更新的 id*/
    let model = req.query.model + "Model"; /*更新的 model */
    let field = req.query.field; /*更新的字段 如:sort */
    let num = req.query.num; /*数量*/

    const result = await appModel[model].find({ _id: id });
    if(result.length > 0) {
        let json = { [field]: num }; // 要更新的数据
        await appModel[model].updateOne({ _id: id }, json);
        res.send({
            success: true,
            message: "修改成功"
        });
    } else {
        res.send({
            success: false,
            message: "传入参数错误"
        });
    }
});


module.exports = router